// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async event => {
  const {
    name,
    source,
    tags,
    limit = 100,
    skip = 0,
    field = 'createAt',
    order = 'desc',
  } = event

  const where = {
    _id: _.neq(null),
    name: name ? new RegExp(name, 'i') : undefined,
    tags: tags ? new RegExp(tags, 'i') : undefined,
    source: source ? new RegExp(source, 'i') : undefined,
  }

  const { total } = await db.collection('video').where(where).count()

  const { data } = await db
    .collection('video')
    .where(where)
    .orderBy(field, order)
    .limit(limit)
    .skip(skip)
    .get()

  return { total, items: data }
}
